import axios from 'axios'
import { ElMessage } from 'element-plus'

import NProgress from 'nprogress'
import 'nprogress/nprogress.css'

// 1.1 创建 axios 实例
const service = axios.create({
  baseURL: '', 
  timeout: 5000 
})

// 1.2 请求拦截
service.interceptors.request.use(config => {
    NProgress.start()

    // 从状态中获取 token
    const token = localStorage.getItem('token')

    if (token) {
      config.headers['Authorization'] = token
    }
    return config
  },
  error => {
    NProgress.done()
    return Promise.reject(error)  
})

// 1.3 响应拦截
service.interceptors.response.use(response => {
    NProgress.done()

    const res = response.data
    if (res.code !== 200) {
      ElMessage({
        message: res.message || 'Error',
        type: 'error',
        duration: 5 * 1000
      })

      return Promise.reject(new Error(res.message || 'Error'))
    } else {
      return res
    }
  },
  error => {
    NProgress.done()

    ElMessage({
      message: error.message,
      type: 'error',
      duration: 5 * 1000
    })

    return Promise.reject(error)
})

export default service